package com.itheima.service.system.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.system.DeptDao;
import com.itheima.domain.system.Dept;
import com.itheima.factory.MapperFactory;
import com.itheima.service.system.DeptService;
import com.itheima.utils.TransactionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class DeptServiceImpl implements DeptService {
    @Override
    public List<Dept> findAll() {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        DeptDao mapper = MapperFactory.getMapper(sqlSession, DeptDao.class);
        List<Dept> all = mapper.findAll();
        TransactionUtil.close(sqlSession);

        return all;
    }

    @Override
    public Dept findById(String id) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        DeptDao mapper = MapperFactory.getMapper(sqlSession, DeptDao.class);
        Dept dept = mapper.findById(id);
        TransactionUtil.close(sqlSession);
        return dept;
    }

    @Override
    public int delete(String id) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        DeptDao mapper = MapperFactory.getMapper(sqlSession, DeptDao.class);
        int rst = mapper.delete(id);
        TransactionUtil.commit(sqlSession);
        this.findAll();
        TransactionUtil.close(sqlSession);
        return rst;
    }

    @Override
    public int save(Dept dept) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        DeptDao mapper = MapperFactory.getMapper(sqlSession, DeptDao.class);
        int rst = mapper.save(dept);
        TransactionUtil.commit(sqlSession);
        this.findAll();
        TransactionUtil.close(sqlSession);
        return rst;
    }

    @Override
    public int update(Dept dept) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        DeptDao mapper = MapperFactory.getMapper(sqlSession, DeptDao.class);

        int rst = mapper.update(dept);
        TransactionUtil.commit(sqlSession);
        this.findAll();
        TransactionUtil.close(sqlSession);
        return rst;
    }

    @Override
    public PageInfo findAll(int currentPage, int PageSize) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        DeptDao mapper = MapperFactory.getMapper(sqlSession, DeptDao.class);
        PageHelper.startPage(currentPage, PageSize);
        List<Dept> all = mapper.findAll();
        PageInfo pageInfo = new PageInfo(all);

        TransactionUtil.close(sqlSession);

        return pageInfo;
    }
}
